package com.community.process._1010.config;

import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.support.config.FastJsonConfig;
import com.community.process._1010.config.jackson.CustomLocalDateTimeDeserializer;
import com.community.process._1010.config.jackson.CustomLocalDateTimeSerializer;
import com.community.process._1010.config.jackson.ToStringOrIntSerializer;
import com.community.process._1010.config.property.ProcessProperty;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.support.converter.SmartMessageConverter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

@Configuration
@EnableConfigurationProperties(ProcessProperty.class)
@EnableRabbit
public class AutoCommonConfig {

    @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
    private String pattern;

    /**
     * Date格式化字符串
     */
    private static final String DATE_FORMAT = "yyyy-MM-dd";

    /**
     * DateTime格式化字符串
     */
    private static final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

    /**
     * Time格式化字符串
     */
    private static final String TIME_FORMAT = "HH:mm:ss";

    @Bean
    public CustomLocalDateTimeSerializer customLocalDateTimeSerializer() {
        String format = StringUtils.hasLength(pattern)? pattern : DATETIME_FORMAT;
        return new CustomLocalDateTimeSerializer(DateTimeFormatter.ofPattern(format));
    }

    @Bean
    public CustomLocalDateTimeDeserializer customLocalDateTimeDeserializer() {
        return new CustomLocalDateTimeDeserializer();
    }

    /**
     * fastJson2MessageConverter
     * 使用fastjson2做为消息转换器
     * 生成消息id
     *
     * @return fastJson2MessageConverter
     */
    @Bean
    public SmartMessageConverter fastJson2MessageConverter() {
        FastJson2MessageConvert messageConvert = new FastJson2MessageConvert();
        FastJsonConfig config = messageConvert.getConfig();
        config.setJSONB(true);
        config.setWriterFeatures(
                JSONWriter.Feature.WriteClassName,
                JSONWriter.Feature.FieldBased,
                JSONWriter.Feature.ReferenceDetection,
                JSONWriter.Feature.NotWriteDefaultValue,
                JSONWriter.Feature.NotWriteHashMapArrayListClassName,
                JSONWriter.Feature.WriteNameAsSymbol
        );
        config.setReaderFeatures(
                JSONReader.Feature.UseDefaultConstructorAsPossible,
                JSONReader.Feature.UseNativeObject,
                JSONReader.Feature.SupportAutoType,
                JSONReader.Feature.IgnoreAutoTypeNotMatch,
                JSONReader.Feature.FieldBased
        );
        messageConvert.setCreateMessageIds(Boolean.TRUE);
        return messageConvert;
    }

    /**
     * Jackson全局转化long类型为String，解决jackson序列化时long类型缺失精度问题
     * @return Jackson2ObjectMapperBuilderCustomizer 注入的对象
     */
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return jacksonObjectMapperBuilder -> {
            // 日期时间格式
            jacksonObjectMapperBuilder.serializerByType(LocalDateTime.class,customLocalDateTimeSerializer());
            jacksonObjectMapperBuilder.deserializerByType(LocalDateTime.class,customLocalDateTimeDeserializer());
            jacksonObjectMapperBuilder.serializerByType(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DATE_FORMAT)));
            jacksonObjectMapperBuilder.deserializerByType(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DATE_FORMAT)));
            jacksonObjectMapperBuilder.serializerByType(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(TIME_FORMAT)));
            jacksonObjectMapperBuilder.deserializerByType(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(TIME_FORMAT)));
            jacksonObjectMapperBuilder.serializerByType(Long.TYPE, ToStringOrIntSerializer.instance);
            jacksonObjectMapperBuilder.serializerByType(Long.class, ToStringOrIntSerializer.instance);
        };
    }
}
